﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ModelLayer;
using System.IO;

namespace ViewLayer.Patients
{
    public partial class PatientInformationView : Form
    {
        MedAgendaEntities entities = new MedAgendaEntities();
        private Guid ordOID = Guid.Empty;
        private Guid patOID = Guid.Empty;
        public bool medicalHistory = false;

        public PatientInformationView()
        {
            InitializeComponent();
        }

        public PatientInformationView(string poid, bool cancelButtonVisible)
        {
            InitializeComponent();
            if (!cancelButtonVisible)
            {
                this.toolStripButtonCancel.Text = "Cancelar";
                this.patientProfile_BindingNavigatorSaveItem.Text = "Guardar";
                this.toolStripButtonContinue.Visible = cancelButtonVisible;
            }
            sex_ComboBox.DataSource = from s in entities.SexEnum_ select s.Value_;
            equipment_ComboBox.DataSource = from e in entities.TelephoneUseEnum_ select e.Value_;
            religion_ComboBox.DataSource = from r in entities.ReligionEnum_ where r.Deactivated_.Equals(false) select r.Value_;
            primaryLanguage_ComboBox.DataSource = from p in entities.SpokenLanguageEnum_ select p.Value_;
            relationship_ComboBox.DataSource = from r in entities.ContactPersonRelationshipEnum_ select r.Value_;
            addressType_ComboBox.DataSource = from a in entities.AddressTypeEnum_ select a.Value_;
            type_ComboBox1.DataSource = from c in entities.ContactPersonTypeEnum_ select c.Value_;
            mrnAssigningAuthority_ComboBox.DataSource = from m in entities.InformationAuthorityEnum_ select m.Value_;

            Guid pOid = Guid.Parse(poid);
            patOID = pOid;
            var patient = entities.PatientProfile_.Where(x => x.OID_.Equals(pOid)).First();
            mrnId_Label1.Text = patient.MrnId_;
            if (patient.Prefix_ == null)
                prefix_ComboBox.SelectedIndex = 0;
            else
                prefix_ComboBox.SelectedItem = patient.Prefix_;
            idDocumentNumber_TextBox.Text = patient.IdDocumentNumber_;
            familyName_TextBox.Text = patient.FamilyName_;
            givenName_TextBox.Text = patient.GivenName_;
            middleName_TextBox.Text = patient.MiddleName_;
            dateOfBirth_DateTimePicker.Text = patient.DateOfBirth_.ToString();
            degree_TextBox.Text = patient.Degree_;
            sex_ComboBox.SelectedItem = patient.SexEnum_.Value_;
            primaryLanguage_ComboBox.SelectedItem = patient.SpokenLanguageEnum_.Value_;
            religion_ComboBox.SelectedItem = patient.ReligionEnum_.Value_;

            var patientAddres = patient.PatientProfileAddress_.Where(x => x.PatientProfile__OID_.Equals(pOid)).First();
            street_TextBox.Text = patientAddres.Street_;
            city_TextBox.Text = patientAddres.City_;
            province_TextBox.Text = patientAddres.Province_;
            country_TextBox.Text = patientAddres.Country_;
            postalCode_TextBox.Text = patientAddres.PostalCode_;
            addressType_ComboBox.SelectedItem = patientAddres.AddressTypeEnum_.Value_;

            number_TextBox.Text = patient.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pOid) && x.TelephoneEquipmentEnum__Code_.Equals("PH")).First().Number_;
            extension_TextBox.Text = patient.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pOid) && x.TelephoneEquipmentEnum__Code_.Equals("PH")).First().Extension_;
            equipment_ComboBox.SelectedItem = patient.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pOid) && x.TelephoneEquipmentEnum__Code_.Equals("PH")).First().TelephoneUseEnum_.Value_;
            txtMobileNumber.Text = patient.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(pOid) && x.TelephoneEquipmentEnum__Code_.Equals("CP")).First().Number_;
            emailAddress_TextBox.Text = patient.PatientProfileEmailAddress_.Where(x => x.PatientProfile__OID_.Equals(pOid)).First().Address_;

            var patientContact = patient.PatientProfileContactPerson_.Where(x => x.PatientProfile__OID_.Equals(pOid)).First();
            name_TextBox.Text = patientContact.Name_;
            address_TextBox.Text = patientContact.Address_;
            homePhone_TextBox.Text = patientContact.HomePhone_;
            businessPhone_TextBox.Text = patientContact.BusinessPhone_;
            type_ComboBox1.SelectedItem = patientContact.ContactPersonTypeEnum_.Value_;
            relationship_ComboBox.SelectedItem = patientContact.ContactPersonRelationshipEnum_.Value_;

            mrnAssigningAuthority_ComboBox.SelectedItem = patient.InformationAuthorityEnum_.Value_;
            healthcardId_TextBox.Text = patient.HealthcardId_;
            healthcardExpiryDate_DateTimePicker.Text = patient.HealthcardExpiryDate_.ToString();

            LoadPatienHistory(pOid);
        }

        private void LoadPatienHistory(Guid poid)
        {
            var pastVisits = (from o in entities.Order_
                              from p in entities.PatientProfile_
                              from v in entities.Visit_
                              where p.OID_.Equals(poid)
                              && o.Visit__OID_.Equals(v.OID_)
                              && p.Patient__OID_.Equals(o.Patient__OID_)
                              && !o.OrderStatusEnum_Code_.Equals("CA")
                              && v.IsAppointment_
                              select new
                              {
                                  OID_ = o.OID_,
                                  Fecha = o.EnteredTime_,
                                  Motivo = o.ReasonForStudy_
                              }).OrderByDescending(x => x.Fecha);
            DataGridViewPastVisits.DataSource = pastVisits;
            DataGridViewPastVisits.Columns[0].Visible = false;
        }

        private void PatientInformationView_Load(object sender, EventArgs e)
        {
            labelNombre.Text = familyName_TextBox.Text + ", " + givenName_TextBox.Text;
            if (medicalHistory)
                tabControl1.SelectedTab = tabPage3;
        }

        private void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButtonContinue_Click(object sender, EventArgs e)
        {

        }

        private void patientProfile_BindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            var patient = entities.PatientProfile_.Where(x => x.OID_.Equals(patOID)).First();
            patient.Prefix_ = prefix_ComboBox.SelectedItem.ToString();
            patient.IdDocumentNumber_ = idDocumentNumber_TextBox.Text;
            patient.FamilyName_ = familyName_TextBox.Text;
            patient.GivenName_ = givenName_TextBox.Text;
            patient.MiddleName_ = middleName_TextBox.Text;
            patient.DateOfBirth_ = DateTime.Parse(dateOfBirth_DateTimePicker.Value.ToString());
            patient.Degree_ = degree_TextBox.Text;
            var sexValue = sex_ComboBox.SelectedItem.ToString();
            patient.SexEnum__Code_ = entities.SexEnum_.Where(x => x.Value_.Equals(sexValue)).First().Code_;
            var primaryLanguajeValue = primaryLanguage_ComboBox.SelectedItem.ToString();
            patient.SpokenLanguageEnum__Code_ = entities.SpokenLanguageEnum_.Where(x => x.Value_.Equals(primaryLanguajeValue)).First().Code_;
            var religionValue = religion_ComboBox.SelectedItem.ToString();
            patient.ReligionEnum__Code_ = entities.ReligionEnum_.Where(x => x.Value_.Equals(religionValue)).First().Code_;

            var patientAddres = patient.PatientProfileAddress_.Where(x => x.PatientProfile__OID_.Equals(patOID)).First();
            patientAddres.Street_ = street_TextBox.Text;
            patientAddres.City_ = city_TextBox.Text;
            patientAddres.Province_ = province_TextBox.Text;
            patientAddres.Country_ = country_TextBox.Text;
            patientAddres.PostalCode_ = postalCode_TextBox.Text;
            var addressTypeValue = addressType_ComboBox.SelectedItem.ToString();
            patientAddres.AddressTypeEnum__Code_ = entities.AddressTypeEnum_.Where(x => x.Value_.Equals(addressTypeValue)).First().Code_;

            var patientTelephoneNumber = patient.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(patOID) && x.TelephoneEquipmentEnum__Code_.Equals("PH")).First();
            patientTelephoneNumber.Number_ = number_TextBox.Text;
            patientTelephoneNumber.Extension_ = extension_TextBox.Text;
            var equipmentValue = equipment_ComboBox.SelectedItem.ToString();
            patientTelephoneNumber.TelephoneUseEnum__Code_ = entities.TelephoneUseEnum_.Where(x => x.Value_.Equals(equipmentValue)).First().Code_;

            var patientMobileNumber = patient.PatientProfileTelephoneNumber_.Where(x => x.PatientProfile__OID_.Equals(patOID) && x.TelephoneEquipmentEnum__Code_.Equals("CP")).First();
            patientMobileNumber.Number_ = txtMobileNumber.Text;
            patient.PatientProfileEmailAddress_.Where(x => x.PatientProfile__OID_.Equals(patOID)).First().Address_ = emailAddress_TextBox.Text;

            var patientContact = patient.PatientProfileContactPerson_.Where(x => x.PatientProfile__OID_.Equals(patOID)).First();
            patientContact.Name_ = name_TextBox.Text;
            patientContact.Address_ = address_TextBox.Text;
            patientContact.HomePhone_ = homePhone_TextBox.Text;
            patientContact.BusinessPhone_ = businessPhone_TextBox.Text;
            var combobox1Value = type_ComboBox1.SelectedItem.ToString();
            patientContact.ContactPersonTypeEnum__Code_ = entities.ContactPersonTypeEnum_.Where(x => x.Value_.Equals(combobox1Value)).First().Code_;
            var relationshipValue = relationship_ComboBox.SelectedItem.ToString();
            patientContact.ContactPersonRelationshipEnum__Code_ = entities.ContactPersonRelationshipEnum_.Where(x => x.Value_.Equals(relationshipValue)).First().Code_;
            var assignedAuthValue = mrnAssigningAuthority_ComboBox.SelectedItem.ToString();
            patient.InformationAuthorityEnum_Code_ = entities.InformationAuthorityEnum_.Where(x => x.Value_.Equals(assignedAuthValue)).First().Code_;
            patient.HealthcardId_ = healthcardId_TextBox.Text;
            patient.HealthcardExpiryDate_ = DateTime.Parse(healthcardExpiryDate_DateTimePicker.Value.ToString());


            entities.SaveChanges();
            MessageBox.Show(null, "Los datos del paciente han sido actualizados.", "Actualización", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private void DataGridViewPastVisits_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string orderOid = string.Empty;
            if (e.RowIndex >= 0)
            {
                orderOid = DataGridViewPastVisits.Rows[e.RowIndex].Cells[0].Value.ToString();
                Guid OOid = Guid.Parse(orderOid);
                var selectedVisit = (from v in entities.Procedure_
                                     where v.Order__OID_.Equals(OOid)
                                     select v).SingleOrDefault();
                richTextBoxActualVisit.Rtf = selectedVisit.Description_;
                ordOID = OOid;
            }
        }

        private void DataGridViewPastVisits_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string orderOid = string.Empty;
            if (e.RowIndex >= 0)
            {
                orderOid = DataGridViewPastVisits.Rows[e.RowIndex].Cells[0].Value.ToString();
                Guid OOid = Guid.Parse(orderOid);
                var selectedVisit = (from v in entities.Procedure_
                                     where v.Order__OID_.Equals(OOid)
                                     select v).SingleOrDefault();
                richTextBoxActualVisit.Rtf = selectedVisit.Description_;
                ordOID = OOid;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ordOID.Equals(Guid.Empty))
            {
                var procedure = (from p in entities.Procedure_
                                 where p.Order__OID_.Equals(ordOID)
                                 select p).SingleOrDefault();
                procedure.Description_ = richTextBoxActualVisit.Rtf;
                entities.SaveChanges();
                MessageBox.Show("Se guardo el historial médico satisfactoriamente");
            }
            else
                MessageBox.Show("Error! seleccione una cita para guardar el historial médico");
        }
    }
}
